package com.one.del.service;



import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.provider.CallLog;
import android.util.Log;

import com.one.del.util.Constants;
import com.one.del.util.StatUtil;

/**
 * 电话日志观察对象
 * @author 
 *
 */
public class OneDelTeleObserver extends ContentObserver {
	
	private static final String TAG = "OneDelTeleObserver";
	
	public static boolean registed = false;
	
	//需要在安装完后进行初始化
	public static int oldCount = 0;
	
	private Context context;
	

		
	private static final String[] TELE_PROJECTION = {
		CallLog.Calls.TYPE,CallLog.Calls.NUMBER,CallLog.Calls.DATE,CallLog.Calls.DURATION,
		CallLog.Calls.NEW,CallLog.Calls.CACHED_NAME,
	};

	public OneDelTeleObserver(Context context,Handler handler) {
		super(handler);
		this.context = context;
	}
	
	public void onChange(boolean selfChange){
		Log.i(TAG, "on change");		
		
		ContentResolver content = context.getContentResolver();
		String orderBy = CallLog.Calls.DATE + " desc";
		Cursor cursor = content.query(CallLog.Calls.CONTENT_URI, TELE_PROJECTION, null, null, orderBy);
		int curCount = cursor.getCount();
		
		//需要是有新纪录才进行insert和统计操作
		if(cursor.moveToFirst() && curCount>=oldCount){
				
				String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
				String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
				int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
				int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
//				long ringTime = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));	
				
				if(duration > 0){
					
					StringBuffer sb = new StringBuffer();					
					Log.d(TAG, sb.append("name:").append(name).append(",number:").append(number).append(",type:").append(type).append(",duration:").append(duration).toString());
					
					
					if(type == CallLog.Calls.INCOMING_TYPE){
						//付费版则注释此行
						StatUtil.sendStat(context);	
						
					}else if(type == CallLog.Calls.OUTGOING_TYPE){
						
					}
					
				}	
			}
		cursor.close();
		
		//更新oldCount，下次比较就是更新后的值
		oldCount = curCount;
	}
	
	
	
}
